from tkinter import *

top = Tk()
top.title('计算器')

frame1 = Frame(top,width=360,height=100,relief='flat')
frame2 = Frame(top,width=360,height=440,padx=1,pady=1)

frame1.pack(padx=1,pady=1,fill='x')
frame1.pack_propagate(False) 
frame2.pack(padx=1,pady=1,fill='both',expand=True)

display = Label(frame1,text='',font=("Arial", 18))
display.pack(padx=10,pady=10)

for i in range(4):
    frame2.grid_rowconfigure(i,weight=1)
    frame2.grid_columnconfigure(i,weight=1)

def get_value(event):
    text = event.widget.cget('text')
    if text == '=':
        try:
            result = eval(display['text'])
            display.config(text=str(result))
        except:
            raise '式子有错误'
        

    elif text == '清空':
        display.config(text='')
    else:
        display.config(text=display['text'] + text)
        

btn_text = ['1','2','3','+','4','5','6','-','7','8','9','*','清空','0','/','=']
for i in range(4):
    for j in range(4):
        btn = Button(frame2,text=btn_text[4*i+j],pady=2)
        btn.bind("<Button-1>", get_value)
        btn.grid(row=i,column=j,sticky='nsew',pady=2)


top.mainloop()